#coding:utf-8
# -*- coding: utf-8 -*-
#@Time : 2020/11/5 19:11
#@Author: 王鹏-wangpeng99
#@File : Test.py


import random,time
from model.service import Service
from model.tree import TreeNode,MultiTree
from utils import logutils

logger = logutils.getlogger(__file__)

"""
调用链生成工具类
"""


class ChanMaker:
    # 初始设置，默认构建10行，10列的矩阵微服务
    # 最小分支数为1，最大分支数为5,最大跨越深度3
    def __init__(self, row=10, col=10, minfurcation=1, maxfurcation=5,maxdeep=3):
        self._row = row
        self._col = col
        self._minfurcation = minfurcation
        self._maxfurcation = maxfurcation
        self._maxdeep=maxdeep
        self._services = None
        self._tree=MultiTree('root')

    def mksvcs(self):
        self._services = list()
        for i in range(self._col):
            tmplst = []
            for j in range(self._row):
                tmplst.append(TreeNode(i, j))
            self._services.append(tmplst)
        # for item in self._services:
        #     print(item)

    # 创建嵌套元祖组成的调用链关系,创建一条随机入口的调用链
    def fetchNextSvcs(self, startsvc=None):
        if self._services == None:
            self.mksvcs()
        # 随机选择入口微服务
        if startsvc == None:
            random.seed(int(round(time.time() * 1000000)))
            startsvc = random.choice(self._services[0])
            ret=self.fetchNextSvcs(startsvc)
            self._tree.add(ret)
            # print(ret)
            return ret
        # 选择下面的微服务
        random.seed(int(round(time.time() * 1000000)))
        # 确定分支数
        furcations = random.randint(self._minfurcation, self._maxfurcation)
        random.seed(int(round(time.time() * 1000000)))
        randcol = random.randint(startsvc.x + 1, startsvc.x + self._maxdeep)
        if randcol < self._col:
            random.seed(int(round(time.time() * 1000000)))
            nextsvcs = random.sample(self._services[randcol], k=furcations)
            if furcations>1:
                tmpRoot = MultiTree(str(int(time.time())))
                for nextscv in nextsvcs:
                    tmpRoot.add(self.fetchNextSvcs(nextscv))
                self._tree.add((tmpRoot,startsvc))
                # print(ret)
            else:
                ret=(startsvc,self.fetchNextSvcs(nextsvcs[0]))
                # print(ret)
                return ret
        # 如果随机深度超出了最大深度，则有可能调用连直接结束
        else:
            return (startsvc,None)





if __name__ == '__main__':
    chanmaker = ChanMaker()
    chan = chanmaker.fetchNextSvcs()
    print(chan)

